const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 是否为修改
    id: "",
    // 银行卡号
    bankCardNumber: "",
    // 持卡人姓名
    realName: "",
    // 身份证号
    idCard: "",
    bankName: "请选择所属银行"
  },
  getDetail(id) {
    let api = "getBankcardDetail";
    if (this.data.role != 1) {
      api = "getBankcardUserDetail";
    }
    wx.$apis[api](id).then((res) => {
      if (res.data) {
        const { bankCardNumber, bankName, realName, idCard } = res.data;
        this.setData({
          bankCardNumber,
          bankName,
          realName,
          idCard
        });
      }
    });
  },
  onSubmit() {
    const { id, bankCardNumber, bankName, realName, idCard } = this.data;

    if (wx.$isNull(realName)) {
      return wx.showToast({
        icon: "none",
        title: "请输入持卡人姓名"
      });
    }

    if (wx.$isNull(idCard)) {
      return wx.showToast({
        icon: "none",
        title: "请输入身份证号码"
      });
    }

    if (wx.$isNull(bankName)) {
      return wx.showToast({
        icon: "none",
        title: "请选择一张银行卡"
      });
    }

    if (bankName === "请选择所属银行") {
      return wx.showToast({
        icon: "none",
        title: "请选择一张银行卡"
      });
    }

    if (wx.$isNull(bankCardNumber)) {
      return wx.showToast({
        icon: "none",
        title: "请输入银行卡号码"
      });
    }

    // 交易市场银行卡
    let api = "addBankcard";
    if (id) {
      api = "editBankcard";
    }

    // 用户的银行卡
    if (this.data.role != 1) {
      api = "addBankcardUser";
      if (id) {
        api = "editBankcardUser";
      }
    }

    wx.showLoading({
      title: "添加中..."
    });
    // 添加银行卡用户
    wx.$apis[api]({
      id: id ? id : undefined,
      companyId: app.globalData.userInfo.companyData.companyId,
      bankCardNumber: this.data.bankCardNumber,
      idCard,
      realName,
      bankName
    }).then((res) => {
      wx.navigateBack(); //返回上一个页面
    });
  },
  onSelectChange() {
    const { id, bankCardNumber, idCard, realName, bankName } = this.data;
    wx.navigateTo({
      url: "/pages/management/select-bank-card/index",
      success: (res) => {
        res.eventChannel.emit("acceptDataFromOpenerPage", {
          addbankcard: { id, bankCardNumber, idCard, realName, bankName }
        });
      }
    });
  },
  onShow() {
    wx.getStorage({
      key: "addbankcard",
      success: (res) => {
        const { id, bankCardNumber, idCard, realName, bankName } = res.data.addbankcard;
        this.setData({ id, bankCardNumber, idCard, realName, bankName });
        wx.removeStorage({
          key: "addbankcard"
        });
      }
    });
  },
  init(options) {
    let role = app.globalData.userInfo.role;
    this.setData({
      role
    });
    const { id } = options;
    // 从银行卡管理点击详情过来
    if (id) {
      this.getDetail(id);
      this.setData({
        id
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init(options);
  }
});
